package cn.aitrox.ry.app.web.service.impl;

import cn.aitrox.ry.app.web.service.TaskService;
import cn.aitrox.ry.bean.RespResult;
import cn.aitrox.ry.common.exception.CustomBizException;
import cn.aitrox.ry.common.service.BaseService;
import cn.aitrox.ry.service.anno.dto.anno.ComponentDto;
import cn.aitrox.ry.service.anno.dto.anno.LesionDto;
import cn.aitrox.ry.service.anno.dto.anno.setting.in.AnnoSettingReadInDto;
import cn.aitrox.ry.service.anno.dto.anno.setting.out.AnnoSettingInfoDto;
import cn.aitrox.ry.service.anno.dto.task.TaskDto;
import cn.aitrox.ry.service.anno.dto.task.in.TaskQueryInDto;
import cn.aitrox.ry.service.anno.feign.AnnoSettingFeign;
import cn.aitrox.ry.service.anno.feign.TaskFeign;
import cn.aitrox.ry.util.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TaskServiceImpl extends BaseService implements TaskService {

    @Autowired
    @Lazy
    private TaskFeign taskFeign;

    @Autowired
    @Lazy
    private AnnoSettingFeign annoSettingFeign;

    public List<TaskDto> getTaskList(List<Integer> taskIds) {
        if (ArrayUtil.isEmpty(taskIds)) {
            return new ArrayList<>();
        }
        List<TaskDto> taskList = taskFeign.query(new TaskQueryInDto(taskIds));
        return taskList;
    }

    @Override
    public List<List<Integer>> getTaskSettingComIds(Integer taskId) {
        RespResult<AnnoSettingInfoDto> readResult = annoSettingFeign.read(new AnnoSettingReadInDto(taskId));
        if (!readResult._isOk()) {
            throw new CustomBizException("查询任务设置失败: " + readResult.getMsg());
        }
        List<List<Integer>> result = new ArrayList<>();
        AnnoSettingInfoDto annoSettingInfo = readResult.getData();
        List<ComponentDto> seriesCompList = annoSettingInfo.getSeriesCompList();
        List<LesionDto> lesionList = annoSettingInfo.getLesionList();
        if (!ArrayUtil.isEmpty(seriesCompList)) {
            result.add(seriesCompList.stream().map(ComponentDto::getComponentId).distinct().collect(Collectors.toList()));
        }
        if (!ArrayUtil.isEmpty(lesionList)) {
            List<Integer> imageComIds = new ArrayList<>();
            result.add(imageComIds);
            for (LesionDto lesion : lesionList) {
                if (!ArrayUtil.isEmpty(lesion.getImageCompList())) {
                    for (ComponentDto component : lesion.getImageCompList()) {
                        if (!imageComIds.contains(component.getComponentId())) {
                            imageComIds.add(component.getComponentId());
                        }
                    }
                }
            }
        }
        return result;
    }

}
